package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
@Resource
private EmpService  empService;
    @Override
    public PageResult<Clazz> getPage(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> pageBean = Page.of(page, pageSize);
        //增加查询条件
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null && !name.isEmpty(), Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getEndDate, begin, end);
        //查询分页数据
        pageBean = page(pageBean, queryWrapper);
        //获得班级数据
        List<Clazz> clazzList = pageBean.getRecords();
        //封装班级status
        LocalDate now = LocalDate.now();
        clazzList.forEach(clazz -> {
            if (clazz.getEndDate().isBefore(now)) {
                clazz.setStatus("结课");
            }else if (clazz.getBeginDate().isAfter(now)) {
                clazz.setStatus("未开始");
            }else {
                clazz.setStatus("进行中");
            }
        });
        //得到班主任id，当没有查询到班级的时候，masterIdList为空
        List<Integer> masterIdList = clazzList.stream().map(Clazz::getMasterId).toList();
        //查询班主任数据,当前班主任id不为空时才查询
        if (!masterIdList.isEmpty()){
            List<Emp> empList = empService.listByIds(masterIdList);
            //把班主任名封装到班级数据中
            clazzList.forEach(clazz -> {
                empList.forEach(emp -> {
                    if (clazz.getMasterId() != null && clazz.getMasterId().equals(emp.getId())) {
                        clazz.setMasterName(emp.getName());
                    }
                });
            });
        }
        return new PageResult<>(pageBean.getTotal(), clazzList);
    }
}
